﻿package net.wangit.dev.unit;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.context.LocalContext;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;

public class JoinElementsUI implements UnitInterceptor {

	private static final String SOURCE_UNIT_ID = "net.wangit.dev.unit.ImportElementsUI.source";
	private static final String TARGET_UNIT_ID = "net.wangit.dev.unit.ImportElementsUI.target";
	private static final String CSS_RENAME = "rename";
	private static final String SQL = "select eid,eid id,n,c,a,au from ELEMENT where uid=? order by b,o";

	public JoinElementsUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String targetUnitId = getTargetUnitId();
		String domain = ConsoleDomainUtil.getDomain(ac);
		String sourceUnitId = ActionContextHelper.getRequest2Session(ac,
				"unit.import.source", JoinElementsUI.SOURCE_UNIT_ID, null);
		unit.getElement("source").setDefaultValue(sourceUnitId);
		if (!Checker.isEmpty(domain) && !Checker.isEmpty(sourceUnitId)
				&& !Checker.isEmpty(targetUnitId)) {
			String title = (new StringBuilder(" ")).append(sourceUnitId)
					.append(" --> ").append(targetUnitId).toString();
			unit.getElement("title").setName(title);
			DB db = DBHelper.getDomainDB(domain);
			MapList data = db.query(JoinElementsUI.SQL, sourceUnitId, 2);
			if (!Checker.isEmpty(data)) {
				Unit elements = (Unit) unit.getElement("elements").getObject();
				elements.setData(data);
				MapList targetData = db.query(JoinElementsUI.SQL, targetUnitId,
						2);
				Element id = elements.getElement("id");
				for (int i = 0; i < data.size(); i++) {
					String eid = data.getRow(i).get("eid");
					if (targetData.findRowIndex("eid", eid) >= 0)
						id.setCss(i, JoinElementsUI.CSS_RENAME);
				}

			}
		} else {
			unit.removeElement("import");
		}
		return unit.write(ac);
	}

	public static String getTargetUnitId() {
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		return ActionContextHelper.getRequest2Session(ac, "uid",
				JoinElementsUI.TARGET_UNIT_ID, null);
	}
}
